package com.xja.dubbo.controller;

import com.xja.dubbo.entity.CarShop;
import com.xja.dubbo.entity.Easybuy_product;
import com.xja.dubbo.entity.Easybuy_user;
import com.xja.dubbo.service.ProductService;
import com.xja.dubbo.service.UserService;
import com.xja.dubbo.util.CookieUtil;
import com.xja.dubbo.util.JsonUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ycz
 * @create 2021-12-19-16:10
 */
@Controller
public class ProductCarController {

    private Logger logger = LoggerFactory.getLogger(ProductCarController.class);


    @Reference(url = "dubbo://localhost:20882")
    private UserService userService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductService productService;

    @RequestMapping("showcar")
    public String showcar(Model model,HttpServletRequest request, HttpServletResponse response){
        try {
            logger.info("显示购物车");
            //获取用户信息
            String uuid = CookieUtil.getCookieValue(request,"uuid" );

            //cookie中获取数据
            String carShopStr = CookieUtil.getCookieValue(request, "user_car", true);

            List<CarShop> carShopList =null;

            if(uuid==null || "".equals(uuid)){
                carShopList=JsonUtil.jsonToList(carShopStr, CarShop.class);
                model.addAttribute("carShopList",  carShopList);
                return "BuyCar";
            }

            Easybuy_user loginUser = userService.findLoginUserFromRedis(uuid);

            model.addAttribute("loginUser",loginUser);

            if(carShopStr == null || "".equals(carShopStr)){
                carShopList = productService.findProdFromRedis(loginUser);
                model.addAttribute("carShopList", carShopList);
                logger.info("从redis中获取:"+carShopList);
                return "BuyCar";
            }

           carShopList = JsonUtil.jsonToList(carShopStr, CarShop.class);

            for (CarShop carShop : carShopList) {
                productService.addProductCarToRedis(loginUser, carShop.getProduct(), carShop.getBuyNum());
            }

            CookieUtil.deleteCookie(request, response, "user_car");

            carShopList = productService.findProdFromRedis(loginUser);

            model.addAttribute("carShopList", carShopList);
            logger.info("从redis中获取:"+carShopList);
            return "BuyCar";


        }catch (Exception e){
            logger.error("显示购车失败", e);
        }
        return "redirect:error.html";
    }



    @RequestMapping("addcar")
    public String addcar(Integer pid, @CookieValue(required = false)String uuid, HttpServletRequest request, HttpServletResponse response){

        try {
            Easybuy_user loginUser = userService.findLoginUserFromRedis(uuid);

            Easybuy_product product = productService.selectByPrimaryKey(pid);

            //用户登录把商品信息放入redis
            if(loginUser!=null){
                productService.addProductCarToRedis(loginUser, product, 1);
                 return "redirect:/index";
            }
            //用户未登录，把购物商品存放到cookie中
            //先获取当前cookie中的购物车信息
            String userCar =CookieUtil.getCookieValue(request, "user_car",true);

            //判断是否第一次购买
            List<CarShop> userCarList = null;
            if (userCar==null || "".equals(userCar)){
                userCarList = new ArrayList<>();
            }else {
                userCarList = JsonUtil.jsonToList(userCar, CarShop.class);

            }
            //判断此次购买的商品是否存在与购物车中
            boolean isHave = false;
            for (CarShop carShop : userCarList) {
                if(carShop.getProduct().getId().equals(product.getId())){
                    //存在
                    isHave = true;
                    carShop.setBuyNum(carShop.getBuyNum()+1);
                    break;
                }
            }

            if(isHave == false){
                CarShop carShop = new CarShop();
                carShop.setBuyNum(1);
                carShop.setProduct(product);
                userCarList.add(carShop);
            }

            //购物车保存到cookie中
            userCar = JsonUtil.objectToJson(userCarList);
            logger.info("购物车数据"+userCar);
            CookieUtil.setCookie(request, response, "user_car", userCar, true);
            return "redirect:/index";
        } catch (Exception e) {
            logger.error("添加购物车失败", e);
        }
        return "redirect:error.html";

    }
}
